'use strict';

const Controller = require('egg').Controller;
const SELECT = require('../../../../config/select');
const userAndRole = async (ctx, destory = false) => {
    const body = ctx.request.body;
    const userId = body.userId;
    const roleId = body.roleId;
    const Rules = {
        userId: {
            type: 'objectId',
            keyname: '用户ID'
        },
        roleId: {
            type: 'objectId',
            keyname: '角色ID'
        }
    };
    ctx.proving(Rules);

    await ctx.service.user.userAndRole(userId, roleId, destory);
    ctx.success({
        message: destory ? '角色移除成功' : '角色授予成功'
    })
}

class UserController extends Controller {
    /**
     * 用户查询
     */
    async find() {
        const { ctx } = this;
        const { id, username, name, sex, role, phone, weixin, page, currentPage } = ctx.query;
        const select = SELECT.USER;
        const Rules = {
            id: {
                type: 'objectId',
                required: false
            }
        };
        ctx.proving(Rules, ctx.query);
        let roles;
        if (role) {
            roles = role.split(',')
        }
        // 只有超级管理员可以获取所有用户
        if(id){}
        const user = await ctx.service.user.find({ id, username, name, sex, role: roles, phone, weixin, page, currentPage }, select);
        ctx.success(user);
    }

    /**
     * 获取当前登陆者信息
     */
    async userInfo() {
        const { ctx } = this;
        const select = SELECT.USER;

        const user = await ctx.service.user.find({ id: ctx.state.user._id }, select);
        ctx.success(user);
    }

    /**
     * 获取超级管理员信息
     */
    async adminInfo() {
        const { ctx } = this;
        const select = 'username headImg role name';

        const user = await ctx.service.user.find({ username: 'admin' }, select);
        ctx.success(user);
    }

    /**
     * 新增用户, 普通用户 - 非注册接口 - 超级管理员
     */
    async create() {
        const { ctx } = this;
        const body = ctx.request.body;
        const { username, password, name, sex, phone, weixin, summary, headImg, email } = body
        const Rules = {
            username: {
                type: 'string',
                required: true,
                allowEmpty: false,
                format: /^[0-9a-zA-Z]+$/,
                min: 4,
                max: 15,
                keyname: '用户名',
            },
            password: {
                type: 'password',
                keyname: '密码'
            }
        };
        ctx.proving(Rules);
        // 角色权限认证
        await ctx.powerValidate();

        const user = await ctx.service.user.create({
            username,
            password,
            name,
            sex,
            phone,
            weixin,
            summary,
            headImg,
            email
        });
        ctx.success({ id: user.id });
    }

    /*
    * 修改用户信息
    * */
    async update() {
        const { ctx } = this;
        const body = ctx.request.body;
        const { head, name, sex, phone, email, id, summary, weixin, headImg } = body;

        const Rules = {
            id: {
                type: 'objectId',
                keyname: 'ID'
            },
            head: {
                type: 'url',
                keyname: '用户头像'
            }
        };
        ctx.proving(Rules);
        // 角色权限认证
        await ctx.powerValidate(id);

        const user = await ctx.service.user.update(id, { head, name, sex, phone, email, id, summary, weixin, headImg });

        ctx.success({
            message: '修改成功',
            id: user.id,
            updateAt: this.app.dateFormat(user.updateAt)
        });
    }

    /*
    * 重置用户密码
    * */
    async restPassword() {
        const { ctx } = this;
        const id = ctx.request.body.id;
        const password = ctx.request.body.password || '123456';

        const Rules = {
            id: {
                type: 'objectId',
                keyname: 'ID'
            },
        };

        ctx.proving(Rules);
        // 角色权限认证
        await ctx.powerValidate();

        const user = await ctx.service.user.update(id, { password });
        ctx.success({
            message: '重置密码成功',
            updateAt: this.app.dateFormat(user.updateAt)
        });
    }

    /*
    * 封禁/解封用户
    * */
    async userStatus() {
        const { ctx } = this;
        const body = ctx.request.body;
        const { id, status } = body;
        if (![1, 2].includes(status)) {
            ctx.throw(402, '状态信息传入不正确');
        }
        const Rules = {
            id: {
                type: 'objectId',
                keyname: 'ID'
            },
        };

        ctx.proving(Rules);
        // 角色权限认证
        await ctx.powerValidate();

        const user = await ctx.service.user.update(id, { status });
        ctx.success({
            message: '状态变更成功',
            updateAt: this.app.dateFormat(user.updateAt)
        });
    }

    /*
    * 删除用户
    * */
    async destroy() {
        const { ctx } = this;
        const id = ctx.request.body.id;

        const Rules = {
            id: {
                type: 'objectId',
                keyname: 'ID'
            }
        };

        ctx.proving(Rules);
        // 角色权限认证
        await ctx.powerValidate();

        const user = await ctx.service.user.update(id, { status: 0 });
        ctx.success({
            message: '删除成功',
            updateAt: this.app.dateFormat(user.updateAt)
        });
    }

    /*
    * 为用户添加角色
    * */
    async addRole(destory = false) {
        const { ctx } = this;
        // 角色权限认证
        await ctx.powerValidate();
        await userAndRole(ctx);
    }

    /*
    * 为用户移除角色
    * */
    async destroyRole() {
        const { ctx } = this;
        // 角色权限认证
        await ctx.powerValidate();
        await userAndRole(ctx, true);
    }
}

module.exports = UserController;
